嵌套if语句 matlab 您所在的位置:网站首页 matlab if for嵌套 嵌套if语句 matlab

嵌套if语句 matlab

2024-06-14 01:10| 来源: 网络整理| 查看: 265

if语句里面会包含条件,后边跟一个语句或一组语句,如下所示:

if(condition){ Statement(s); }123

仅当给定条件为真时才执行语句。如果条件为false,那么if语句体内的语句将被完全忽略。

012bea73ace89e7cb4309fcbd112e0bf.png

if语句的示例

public class IfStatementExample { public static void main(String args[]){ int num=70; if( num < 100 ){ /* 打印只会执行一次 * 如果上述条件为真的情况才会执行 */ System.out.println("number is less than 100"); } } }123456789101112

输出:

number is less than 1001 b)嵌套if语句

当在另一个if语句中有if语句时,它将被称为嵌套if语句。 嵌套的结构如下所示:

if(condition_1) { Statement1(s); if(condition_2) { Statement2(s); } }1234567

如果condition_1为true,则执行Statement1。只有条件(condition_1和condition_2)都为真时,Statement2才会执行。 嵌套if语句的示例

public class NestedIfExample { public static void main(String args[]){ int num=70; if( num < 100 ){ System.out.println("number is less than 100"); if(num > 50){ System.out.println("number is greater than 50"); } } } }123456789101112

输出:

number is less than 100 number is greater than 5012 c)if-else语句

if-else语句看起来是这样的:

if(condition) { Statement(s); } else { Statement(s); }123456

如果条件为真,则“if”内的语句将执行,如果条件为假,则“else”内的语句将执行。

92b726873d18596c5e891b1b1c3695f8.png

if-else语句的示例

public class IfElseExample { public static void main(String args[]){ int num=120; if( num < 50 ){ System.out.println("num is less than 50"); } else { System.out.println("num is greater than or equal 50"); } } }123456789101112

输出:

num is greater than or equal 501 d)if-else-if语句

当我们需要检查多个条件时使用if-else-if语句。 在这个声明中,我们只有一个“if”和一个“else”,但是我们可以有多个“else if”。 它看起来是这样的:

if(condition_1) { /*if condition_1 为真执行*/ statement(s); } else if(condition_2) { /* 如果不满足condition_1 * 但是满足condition_2则执行此操作 */ statement(s); } else if(condition_3) { /* 如果不满足condition_1和condition_2 * 但是满足condition_3则执行此操作 */ statement(s); } . . . else { /* 如果上面都不满足 * 执行这个 */ statement(s); }12345678910111213141516171819202122232425

注意:这里要注意的最重要的一点是,在if-else-if语句中,只要满足某条件,就会执行相应的语句,忽略剩余的判断。 如果没有满足的条件,则执行“else”内的语句。

if-else-if程序示例:

public class IfElseIfExample { public static void main(String args[]){ int num=1234; if(num =1) { System.out.println("Its a two digit number"); } else if(num =100) { System.out.println("Its a three digit number"); } else if(num =1000) { System.out.println("Its a four digit number"); } else if(num =10000) { System.out.println("Its a five digit number"); } else { System.out.println("number is not between 1 & 99999"); } } }123456789101112131415161718192021

程序输出:

Its a four digit number1


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有